<template>
  <div class="upload-box">
    <el-upload
      :action="action"
      :headers="headers"
      :data="data"
      :name="name"
      :file-list="fileList"
      :show-file-list="showFileList"
      :drag="drag"
      :accept="accept"
      :multiple="multiple"
      :limit="limit"
      :auto-upload="autoUpload"
      :disabled="disabled"
      :before-upload="handleBeforeUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :http-request="customUpload"
      :list-type="listType"
      :class="uploadClass">
      
      <template v-if="drag">
        <!-- 拖拽上传内容 -->
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      
      <!-- 普通上传 -->
      <el-button v-else :disabled="disabled" :icon="icon" :size="size">
        <slot>{{ buttonText }}</slot>
      </el-button>
      
      <div slot="tip" class="el-upload__tip" v-if="tip">{{ tip }}</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadBox',
  props: {
    // 上传地址
    action: {
      type: String,
      default: ''
    },
    // 请求头
    headers: {
      type: Object,
      default: () => ({})
    },
    // 额外参数
    data: {
      type: Object,
      default: () => ({})
    },
    // 文件字段名
    name: {
      type: String,
      default: 'file'
    },
    // 文件列表
    fileList: {
      type: Array,
      default: () => []
    },
    // 是否显示文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 是否支持拖拽
    drag: {
      type: Boolean,
      default: false
    },
    // 接受的文件类型
    accept: {
      type: String,
      default: ''
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 最大上传数量
    limit: {
      type: Number,
      default: 0
    },
    // 是否自动上传
    autoUpload: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 文件大小限制（MB）
    maxSize: {
      type: Number,
      default: 10
    },
    // 按钮文本
    buttonText: {
      type: String,
      default: '点击上传'
    },
    // 按钮图标
    icon: {
      type: String,
      default: 'el-icon-upload2'
    },
    // 按钮大小
    size: {
      type: String,
      default: 'medium'
    },
    // 提示文本
    tip: {
      type: String,
      default: ''
    },
    // 列表类型
    listType: {
      type: String,
      default: 'text',
      validator: value => ['text', 'picture', 'picture-card'].includes(value)
    },
    // 自定义上传类名
    uploadClass: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentFileList: []
    }
  },
  watch: {
    fileList: {
      handler(newVal) {
        this.currentFileList = [...newVal]
      },
      immediate: true
    }
  },
  methods: {
    // 上传前验证
    handleBeforeUpload(file) {
      // 文件大小验证
      const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize
      if (!isLtMaxSize) {
        this.$message.error(`上传文件大小不能超过 ${this.maxSize}MB!`)
        return false
      }

      // 文件类型验证
      if (this.accept) {
        const acceptTypes = this.accept.split(',')
        const fileType = file.type
        const fileName = file.name
        const isValidType = acceptTypes.some(type => {
          if (type.startsWith('.')) {
            return fileName.toLowerCase().endsWith(type.toLowerCase())
          } else {
            return fileType.includes(type.replace('*', ''))
          }
        })
        
        if (!isValidType) {
          this.$message.error(`只能上传 ${this.accept} 格式的文件!`)
          return false
        }
      }

      // 触发before-upload事件
      this.$emit('before-upload', file)
      return true
    },

    // 文件预览
    handlePreview(file) {
      this.$emit('preview', file)
    },

    // 文件移除
    handleRemove(file, fileList) {
      this.currentFileList = fileList
      this.$emit('remove', file, fileList)
      this.$emit('update:fileList', fileList)
    },

    // 上传成功
    handleSuccess(response, file, fileList) {
      this.currentFileList = fileList
      this.$emit('success', response, file, fileList)
      this.$emit('update:fileList', fileList)
    },

    // 上传失败
    handleError(err, file, fileList) {
      this.$emit('error', err, file, fileList)
    },

    // 超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${this.limit} 个文件`)
      this.$emit('exceed', files, fileList)
    },

    // 文件改变
    handleChange(file, fileList) {
      this.currentFileList = fileList
      this.$emit('change', file, fileList)
      this.$emit('update:fileList', fileList)
    },

    // 自定义上传
    customUpload(options) {
      this.$emit('custom-upload', options)
    },

    // 手动上传
    submit() {
      this.$refs.upload.submit()
    },

    // 清空文件列表
    clearFiles() {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-box {
  width: 100%;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}
</style> 